package com.unionpay.upyzt.spring.example.contorller;


import com.alibaba.fastjson.JSONObject;
import com.unionpay.upyzt.Upyzt;
import com.unionpay.upyzt.exception.InvalidRequestException;
import com.unionpay.upyzt.exception.UpyztException;
import com.unionpay.upyzt.model.SettleAcct;
import com.unionpay.upyzt.model.*;
import com.unionpay.upyzt.resp.*;
import com.unionpay.upyzt.spring.example.entity.*;
import com.unionpay.upyzt.spring.example.service.unionPay.UnionPayService;
import com.unionpay.upyzt.spring.example.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/unionPay")

public class UnionPayController {

    @Autowired
    private UnionPayService unionPayService;




    @GetMapping("/selectAcctInfo/{balanceAcctId}")
    public Map<String,Object> selectAcctInfo(@PathVariable String balanceAcctId) {
        BalanceAcctResp balanceAcctResp = null;
        HashMap<String, Object> map = new HashMap<>();
        try {
            balanceAcctResp = BalanceAcct.retrieveById(balanceAcctId, null);
        } catch (UpyztException e) {
            map.put("code",400);
            map.put("msg",e.getMessage());
            return  map;
        }
        map.put("code",200);
        map.put("data",balanceAcctResp);
        return map;
    }



    @GetMapping("/logoutAcct/{balanceAcctId}")
    public Result logoutAcct(@PathVariable String balanceAcctId) {
        BalanceAcctDeleteResp balanceAcctDeleteResp = null;
        try {
            balanceAcctDeleteResp = BalanceAcct.removeById(balanceAcctId);
        } catch (UpyztException e) {
            throw new RuntimeException(e);
        }
        return ResultGenerator.genSuccessResult(balanceAcctDeleteResp);
    }

    @PostMapping("/addBalanceAcct")
    public Map<String,Object> addBalanceAcct(@RequestBody DeleteAccDto deleteAccDto) {
        HashMap<String, Object> rs = new HashMap<>();
        HashMap<String, Object> map = new HashMap<>();
        BalanceAcctStoreResp balanceAcctStoreResp = null;
        try {
            map.put("out_request_no",deleteAccDto.getOutRequestNo());
            map.put("bank_acct_no", Upyzt.encryptField(deleteAccDto.getBankAcctNo()));
            map.put("bank_acct_type", "1");
            map.put("cus_id", deleteAccDto.getCusId());
            map.put("password", Upyzt.encryptField("169223"));
            balanceAcctStoreResp = BalanceAcct.create(map);
            rs.put("code",200);
            rs.put("data",balanceAcctStoreResp);
            return rs;
        } catch (UpyztException e) {
            rs.put("code",400);
            rs.put("msg",e.getMessage());
            return rs;
        }
    }

/*{
  "balance_acct_id": "2011628376306352201",
  "out_request_no": "DCC_CUS_APPLICATIONS_202501134063211851447_1736753340632",
  "cus_id": "1111576011121283686",
  "mch_id": null,
  "rel_acct_no": "035030001000966914025",
  "metadata": null,
  "request_id": "00e040e1fcec4e0f89530abc18d477f7"
}*/


    @PostMapping("/addNewAcct")
    public Result addNewAcct(@RequestBody DeleteAccDto deleteAccDto)  {
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_request_no",deleteAccDto.getOutRequestNo());
        try {
            map.put("bank_acct_no", Upyzt.encryptField(deleteAccDto.getBankAcctNo()));
        } catch (InvalidRequestException e) {
            throw new RuntimeException(e);
        }
        map.put("bank_acct_type", "1");
        map.put("cus_id", deleteAccDto.getCusId());
        map.put("sms_code", deleteAccDto.getSmsCode());
        SettleAcctResp settleAcctResp = null;
        try {
            settleAcctResp = SettleAcct.create(map);
        } catch (UpyztException e) {
            return  ResultGenerator.genFailResult(e.getMessage());
        }
        return ResultGenerator.genSuccessResult(settleAcctResp);
    }

    @PostMapping("/addNewAcctnew2")
    public Result addNewAcctnew2(@RequestBody DeleteAccDto deleteAccDto)  {
    /*    HashMap<String, Object> map = new HashMap<>();
        map.put("out_request_no",getNo());
        map.put("bank_acct_type", "1");
      *//*  map.put("bank_code", deleteAccDto.getBankCode());
        map.put("bank_branch_code", deleteAccDto.getBankBranchCode());*//*
        map.put("cus_id", deleteAccDto.getCusId());
        map.put("sms_code", deleteAccDto.getSmsCode());
        map.put("extra",deleteAccDto.getExtra());
        SettleAcctResp settleAcctResp = null;
        try {
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("code",deleteAccDto.getBankAcctNo());
            HttpResult httpResult = HttpUtil.doPost("http://localhost:15551/test/getStr",map1);
            map.put("bank_acct_no", httpResult.getBody());
            settleAcctResp = SettleAcct.create(map);
        } catch (UpyztException e) {
            return  ResultGenerator.genFailResult(e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }*/
        return ResultGenerator.genSuccessResult();
    }


    @GetMapping("/queryAcctInfoById/{settleAcctId}")
    public Map<String,Object> queryAcctInfoById(@PathVariable String settleAcctId) {
        SettleAcctResp settleAcctResp = null;
        Map<String,Object> map = new HashMap<>();
        try {
            settleAcctResp = SettleAcct.retrieveById(settleAcctId, null);
        } catch (UpyztException e) {
            map.put("code",400);
            map.put("msg",e.getMessage());
            return  map;
        }
        map.put("code",200);
        map.put("data",settleAcctResp);
        return map;
    }

    @GetMapping("/queryAcctInfoByOutRequestNo/{settleAcctId}")
    public Result queryAcctInfoByOutRequestNo(@PathVariable String outRequestNo) {
        SettleAcctResp settleAcctResp = null;
        try {
            settleAcctResp = SettleAcct.retrieveByOutRequestNo(outRequestNo, null);
        } catch (UpyztException e) {
            return  ResultGenerator.genFailResult(e.getMessage());
        }
        return ResultGenerator.genSuccessResult(settleAcctResp);
    }

    @PostMapping("/queryAcctInfoByUserId")
    public Result queryAcctInfoByUserId(@RequestBody DeleteAccDto deleteAccDto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("cus_id", deleteAccDto.getCusId());
        SettleAcctListResp settleAcctListResp = null;
        try {
            settleAcctListResp = SettleAcct.retrieveByUserId(map, null);
        } catch (UpyztException e) {
            return  ResultGenerator.genFailResult(e.getMessage());
        }
        return ResultGenerator.genSuccessResult(settleAcctListResp);
    }

    /**
     * 删除银行卡
     * @param deleteAccDto
     * @return
     * @throws InvalidRequestException
     */
    @PostMapping("/delAcctInfo")
    public Result delAcctInfo(@RequestBody DeleteAccDto deleteAccDto) throws InvalidRequestException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("bank_acct_no", Upyzt.encryptField(deleteAccDto.getBankAcctNo()));
        if (StringUtil.isNotEmpty(deleteAccDto.getCusId())){
            map.put("cus_id", deleteAccDto.getCusId());
        }
        if (StringUtil.isNotEmpty(deleteAccDto.getMchId())){
            map.put("mch_id", deleteAccDto.getMchId());
        }
        SettleAcctDeleteResp settleAcctDeleteResp = null;
        try {
            settleAcctDeleteResp = SettleAcct.removeByParams(map,null);
        } catch (UpyztException e) {
           return ResultGenerator.genFailResult(e.getMessage());
        }
        return ResultGenerator.genSuccessResult(settleAcctDeleteResp);
    }

    /**
     * 新增银行卡
     * @param deleteAccDto
     * @return
     */
    @PostMapping("/addAcctInfo")
    public Map<String, Object> addAcctInfo(@RequestBody DeleteAccDto deleteAccDto){
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> rs = new HashMap<>();
        params.put("out_request_no", getNo());
        params.put("cus_id", deleteAccDto.getCusId());
        params.put("bank_acct_type", "1");
        try {
            params.put("bank_acct_no",Upyzt.encryptField(deleteAccDto.getBankAcctNo()));
            params.put("sms_code",deleteAccDto.getSmsCode());
        } catch (InvalidRequestException e) {
            rs.put("code",400);
            rs.put("msg",e.getMessage());
            return rs;
        }
        try {
            SettleAcctResp settleAcctResp = SettleAcct.create(params);
            rs.put("code",200);
            rs.put("msg",settleAcctResp);
            return rs;
        } catch (UpyztException e) {
            rs.put("code",400);
            rs.put("msg",e.getMessage()+";"+e.getIssue());
            return rs;
        }
    }


    @PostMapping("/transferAccounts")
    public Map<String,Object> transferAccounts(@RequestBody TransferAccountsDto transferAccountsDto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_order_no",getNo());
        map.put("amount",transferAccountsDto.getAmount());
        map.put("pay_balance_acct_id",transferAccountsDto.getPayBalanceAcctId());
        map.put("recv_balance_acct_id",transferAccountsDto.getRecvBalanceAcctId());
        try {
            map.put("password", Upyzt.encryptField(transferAccountsDto.getPassword()));
        } catch (InvalidRequestException e) {
            throw new RuntimeException(e);
        }
        /*  map.put("acct_type","BANK_FUND");*/
        ArrayList<Object> objects = new ArrayList<>();
        HashMap<String, String> product = new HashMap<>();
        product.put("order_no", StringUtil.getUUid());
        product.put("order_amount","100");
        product.put("product_name","转账");
        product.put("product_count","1");
        objects.add(product);
        ArrayDto arrayDto = new ArrayDto(objects);
        map.put("extra",arrayDto);
        System.out.println("---->>>"+JSONObject.toJSONString(map));
        PaymentResp paymentResp = null;
        try {
            paymentResp = Payment.create(map, null);
        } catch (UpyztException e) {
            map.put("code",400);
            map.put("msg",e.getMessage());
        }
        map.put("code",200);
        map.put("data",paymentResp);
        return   map;
    }


    @PostMapping("/freeze")
    public Result freeze(@RequestBody WithdrawalDto withdrawalDto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_request_no",getNo());
        map.put("freeze",withdrawalDto.getFreeze());
        map.put("balance_acct_id",withdrawalDto.getBalanceAcctId());
        /*  map.put("acct_type","BANK_FUND");*/
        System.out.println("---->>>"+JSONObject.toJSONString(map));
        BalanceAcctFreezeResp balanceAcctFreezeResp = null;
        try {
            balanceAcctFreezeResp = BalanceAcctFreeze.create(map, null);
        } catch (UpyztException e) {
            throw new RuntimeException(e);
        }
        return   ResultGenerator.genSuccessResult(balanceAcctFreezeResp);
    }



    @PostMapping("/getResetPasswordSmsCode")
    public Result getResetPasswordSmsCode(@RequestBody WithdrawalDto withdrawalDto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("balance_acct_id",withdrawalDto.getBalanceAcctId());
        /*  map.put("acct_type","BANK_FUND");*/
        System.out.println("---->>>"+JSONObject.toJSONString(map));
        AcctPasswordResp acctPasswordResp = null;
        try {
            acctPasswordResp = AcctPassword.smsCode(map, null);
        } catch (UpyztException e) {
            throw new RuntimeException(e);
        }
        return   ResultGenerator.genSuccessResult(acctPasswordResp);
    }


    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody WithdrawalDto withdrawalDto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("balance_acct_id",withdrawalDto.getBalanceAcctId());
        map.put("sms_code",withdrawalDto.getSmsCode());
        System.out.println("---->>>"+JSONObject.toJSONString(map));
        AcctPasswordResp acctPasswordResp = null;
        try {
            map.put("new_password",Upyzt.encryptField(withdrawalDto.getNewPassword()));
            acctPasswordResp = AcctPassword.reset(map, null);
        } catch (UpyztException e) {
            throw new RuntimeException(e);
        }
        return   ResultGenerator.genSuccessResult(acctPasswordResp);
    }


    @PostMapping("/withdrawalAccounts")
    public HashMap<String, Object> withdrawalAccounts(@RequestBody WithdrawalDto withdrawalDto) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_order_no",getNo());
        map.put("amount",withdrawalDto.getAmount());
        map.put("balance_acct_id",withdrawalDto.getBalanceAcctId());
        WithdrawalResp withdrawalResp = null;
        HashMap<String, Object> map1 = new HashMap<>();
        try {
            map.put("password",Upyzt.encryptField(withdrawalDto.getPassword()));
            map.put("bank_acct_no", Upyzt.encryptField(withdrawalDto.getBankAcctNo()));

            /*  map.put("acct_type","BANK_FUND");*/
            System.out.println("---->>>"+JSONObject.toJSONString(map));

            withdrawalResp = Withdrawal.create(map, null);
        } catch (UpyztException e) {
            map1.put("code",400);
            map1.put("msg",e.getMessage());
            return map1;
        }
        map1.put("code",200);
        map1.put("data",withdrawalResp);
        return   map1;
    }

    @PostMapping("/selectInfoByUserId")
    public Map<String,Object> selectInfoByUserId(@RequestBody BalanceAcctDto balanceAcctDto) {
        Map<String, Object> rs = new HashMap<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("cus_id",balanceAcctDto.getCusId());
        System.out.println("---->>>"+JSONObject.toJSONString(map));
        BalanceAcctListResp balanceAcctStoreResp = null;
        try {
            SettleAcctListResp settleAcctListResp = SettleAcct.retrieveByUserId(map);
            System.out.println(settleAcctListResp);
            rs.put("code",200);
            rs.put("data",settleAcctListResp);
            return   rs;
        } catch (UpyztException e) {
            rs.put("code",400);
            rs.put("msg",e.getMessage());
            return rs;
        }
    }



    @PostMapping("/delAcct")
    public  Map<String,Object> delAcct(@RequestBody DeleteAccDto deleteAccDto){
        Map<String, Object> rs = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        try {
           map.put("cus_id",deleteAccDto.getCusId());
            map.put("bank_acct_no",Upyzt.encryptField(deleteAccDto.getBankAcctNo()));
            SettleAcctDeleteResp settleAcctDeleteResp = SettleAcct.removeByParams(map,null);
            System.out.println(settleAcctDeleteResp.toString());
        } catch (UpyztException e) {
            rs.put("code",400);
            rs.put("msg",e.getMessage());
            return rs;
        }
        rs.put("code",200);
        rs.put("msg","删除成功");
        return rs;
    }

    private String getNo() {
        long currentTimeMillis = System.currentTimeMillis();
        return "DUO_CHI_CAI_"+ StringUtil.getBillno()+"_" +currentTimeMillis;
    }

    @PostMapping("/incoming")
    @ResponseBody
    public Map<String, Object> incoming(@RequestBody Incoming incomingDto) {
       return unionPayService.personalValidationIncoming(incomingDto);
    }

    @ResponseBody
    @PostMapping("/sendCode")
    public Result sendCode(@RequestParam String phoneNumber) {
        Map<String, Object> mobileVerificationCode = unionPayService.getMobileVerificationCode(phoneNumber);
        return ResultGenerator.genFailResult(mobileVerificationCode.toString());
    }

//    @PostMapping("/addNewAcctnew")
//    @ApiOperation(value = "新增银行账户2",notes = "新增银行账户",httpMethod = "POST")
//    public Result addNewAcctnew(@RequestBody DeleteAccDto deleteAccDto)  {
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("out_request_no",getNo());
//        map.put("bank_acct_type", "1");
//      /*  map.put("bank_code", deleteAccDto.getBankCode());
//        map.put("bank_branch_code", deleteAccDto.getBankBranchCode());*/
//        map.put("cus_id", deleteAccDto.getCusId());
//        map.put("sms_code", deleteAccDto.getSmsCode());
//        map.put("extra",deleteAccDto.getExtra());
//        SettleAcctResp settleAcctResp = null;
//        try {
//            map.put("bank_acct_no", Upyzt.encryptField(deleteAccDto.getBankAcctNo()));
//            settleAcctResp = SettleAcct.create(map);
//        } catch (UpyztException e) {
//            return  ResultGenerator.genFailResult(e.getMessage());
//        }
//        return ResultGenerator.genSuccessResult(settleAcctResp);
//    }




}
